package com.woniuxy.ssh.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.woniuxy.ssh.dao.BaseDao;
import com.woniuxy.ssh.utils.PageInfo;

public abstract class BaseDaoImp<T> implements BaseDao<T> {
	
	private Class<T> clazz;
	
	@SuppressWarnings("unchecked")
	public BaseDaoImp() {
		ParameterizedType type= (ParameterizedType) this.getClass().getGenericSuperclass();//瀵版鍩屽▔娑樼�閻ㄥ嫮鍩楃猾锟�		
		this.clazz=(Class<T>) type.getActualTypeArguments()[0];
	}
	
	@Resource
	private SessionFactory sessionFactory;

	@Override
	public void saveEntity(T t) {
		sessionFactory.getCurrentSession().save(t);
	}

	@Override
	public void deleteEntity(T t) {
		sessionFactory.getCurrentSession().delete(t);
	}

	@Override
	public void updateEntity(T t) {
		sessionFactory.getCurrentSession().update(t);
	}

	@Override
	public T getEntity(Serializable id) {
		return (T) sessionFactory.getCurrentSession().get(clazz, id);
	}

	@Override
	public T loadEntity(Serializable id) {
		return (T) sessionFactory.getCurrentSession().load(clazz, id);
	}

	@Override
	public List<T> findEntityByHQL(String hql, Object... objects) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		for(int i=0;i<objects.length;i++){
			query.setParameter(i, objects[i]);
		}
		return query.list();
	}

	@Override
	public void executeUpdateByHQL(String hql, Object... objects) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		for(int i=0;i<objects.length;i++){
			query.setParameter(i, objects[i]);
		}
		query.executeUpdate();
	}
	
	@Override
	public List<T> findEntityByPageInfo(PageInfo pageInfo, String hql,
			Object... object) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		for(int i=0;i<object.length;i++){
			query.setParameter(i, object[i]);
		}
		pageInfo.setTotalResult(query.list().size());//寰楀埌鎬荤殑璁板綍鏉℃暟
		//鍐嶈繘琛屽垎椤靛鐞�
		query.setFirstResult(pageInfo.getBeginResult());
		query.setMaxResults(pageInfo.getPageSize());
		
		return query.list();
	}
	

}














